﻿using System;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Songhay.Tests
{
    using Extensions;
    using Songhay.Net;

    [TestClass]
    public class WcfTest
    {
        [TestInitialize]
        public void ClearPreviousTestResults()
        {
            var directory = Directory.GetParent(TestContext.TestDir);

            directory.GetFiles()
                .OrderByDescending(f => f.LastAccessTime).Skip(1)
                .ForEachInEnumerable(f => f.Delete());

            directory.GetDirectories()
                .OrderByDescending(d => d.LastAccessTime).Skip(1)
                .ForEachInEnumerable(d => d.Delete(true));
        }

        /// <summary>
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///</summary>
        public TestContext TestContext { get; set; }

        [TestMethod]
        [Description("Should list Service One data.")]
        public void ShouldListServiceOneData()
        {
            var client = new ServiceOneReference.WcfServiceOneClient();

            Assert.IsNotNull(client, "The expected WCF Client is not here.");

            var list = client.ListServiceOneData();

            Assert.IsNotNull(list, "The expected list is not here.");

            var data = list.First<ServiceOneReference.ServiceOneData>();

            Assert.IsNotNull(data, "The expected data is not here.");
        }

        [TestMethod]
        [Description("Should list Service One data.")]
        public void ShouldListServiceOneAjaxData()
        {
            var uri = new Uri("http://songhay7v/sites/DebugHostRoot/Services/WcfServiceOne.svc/json/ListServiceOneDataForAjax");
            var s = HttpVerbUtility.Get(uri);
            Assert.IsNotNull(s, "The expected JSON string is not here.");

            var clientSerializer = new DataContractJsonSerializer(typeof(ServiceOneReference.ServiceOneData[]));
            using(var stream = new MemoryStream(Encoding.Unicode.GetBytes(s)))
            {
                var clientObject = clientSerializer.ReadObject(stream) as ServiceOneReference.ServiceOneData[];
                Assert.IsNotNull(clientObject);
            }
        }
    }
}
